package com.lhn.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.client.ZKClientConfig;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

/**
 * 〈一句话功能简述>
 * 〈〉
 *
 * @Author 17505
 * @Create 2022/3/11
 * @Since 1.0.0
 */
public class ZkClient {

    /**
     * 服务器地址
     * */
    private String connectString = "192.168.3.33:2181,192.168.3.34:2128,192.168.3.19:2181";

    /**
     * 超时时间
     * */
    private int sessionTimout = 2000;

    public ZooKeeper zooKeeper;

    /**
     * 初始化操作，连接 Zookeeper 集群。
     * */
    @Before
    public void init() {
        ZKClientConfig config = new ZKClientConfig();
        config.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY, "false");
        try {
            zooKeeper = new ZooKeeper(connectString, sessionTimout, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    System.out.println("----------------------------");
                    List <String> children = null;
                    try {
                        children = zooKeeper.getChildren("/", true);
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    for (String child : children) {
                        System.out.println(child);
                    }
                    System.out.println("----------------------------");
                }
            }, config);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建子节点
     * */
    @Test
    public void create() throws KeeperException, InterruptedException {
        String nodeCreate = zooKeeper.create("/lol", "lubu".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    /**
     * 创建监听
     * */
    @Test
    public void getChildren() throws KeeperException, InterruptedException {
        List<String> children = zooKeeper.getChildren("/", true);
        for (String child : children) {
            System.out.println(child);
        }
        // 延迟
        Thread.sleep(Integer.MAX_VALUE);
    }

    /**
     * 判断节点是否存在
     * */
    @Test
    public void exist() throws KeeperException, InterruptedException {
        Stat exists = zooKeeper.exists("/lol", false);
        System.out.println(exists == null ? "not exit" : exists);
    }
}